#include <iostream>
#include <string>
#include "sock.hpp"

void Usage(std::string proc){
  std::cout<< "Usage\n\t" << proc << "server_ip server_port" << std::endl;
}
int main(int argc, char* argv[]){
  if(argc != 3){//   ./client_udp server_ip server_port
    Usage(argv[0]);
    return 0;
  }
  int sock = sock::Sock_for_Udp();
  if(sock < 0){
    std::cerr<<"sockket error" <<std::endl;
    return 1;
  }
  struct sockaddr_in server;
  server.sin_family = AF_INET;
  server.sin_port = htons(atoi(argv[2]));
  server.sin_addr.s_addr = inet_addr(argv[1]);
  while(1){
    std::cout << "client say #";
    char line[1024];
    fgets(line, sizeof(line), stdin);
    sendto(sock, line, sizeof(line), 0, (struct sockaddr*)&server, sizeof(server));

    struct sockaddr_in tmp;
    socklen_t len = sizeof(tmp);
    char buffer[1024];
    ssize_t s = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr*)&tmp, &len);
    if(s > 0){
      buffer[s] = 0;
      std::cout << buffer <<std::endl;
    }
    else{
      std::cerr<< "recvfrom error" <<std::endl;
    }
  }
  return 0;
}
